// i2c_utils.c
#include "i2c_master_utils.h"
#include "esp_log.h"
// 标记 I2C 驱动是否已经安装
static bool i2c_installed = false;

esp_err_t i2c_master_init(void) {
    if (!i2c_installed) {
        i2c_config_t conf = {
                .mode = I2C_MODE_MASTER,
                .scl_io_num = I2C_MASTER_SCL_IO,
                .sda_io_num = I2C_MASTER_SDA_IO,
                .scl_pullup_en = GPIO_PULLUP_ENABLE,
                .sda_pullup_en = GPIO_PULLUP_ENABLE,
                .master.clk_speed = I2C_MASTER_FREQ_HZ
        };
        esp_err_t err = i2c_param_config(I2C_MASTER_PORT_NUM, &conf);
        if (err != ESP_OK) {
            ESP_LOGE("I2C", "I2C parameter configuration failed: %d", err);
            return err;
        }
        err = i2c_driver_install(I2C_MASTER_PORT_NUM, conf.mode, 0, 0, 0);
        if (err == ESP_OK) {
            i2c_installed = true;
            ESP_LOGI("I2C", "I2C driver installed successfully");
        } else {
            ESP_LOGE("I2C", "I2C driver installation failed: %d", err);
        }
        return err;
    }
    return ESP_OK;
}
// 扫描 I2C 总线
void i2c_scan() {
    ESP_LOGI("I2C", "Scanning I2C bus...");
    uint8_t device_count = 0;
    for (uint8_t address = 0x03; address < 0x78; address++) {
        i2c_cmd_handle_t cmd = i2c_cmd_link_create();
        i2c_master_start(cmd);
        i2c_master_write_byte(cmd, (address << 1) | I2C_MASTER_WRITE, true);
        i2c_master_stop(cmd);
        esp_err_t err = i2c_master_cmd_begin(I2C_MASTER_PORT_NUM, cmd, pdMS_TO_TICKS(100));
        i2c_cmd_link_delete(cmd);

        if (err == ESP_OK) {
            ESP_LOGI("I2C", "Device found at address 0x%02X", address);
            device_count++;
        }
    }
    if (device_count == 0) {
        ESP_LOGI("I2C", "No I2C devices found.");
    }
}